#!/usr/bin/env python
# coding=utf-8




import os

from PyQt5.QtCore import pyqtSlot, Qt
#from PyQt5.QtCore import *
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QTableWidgetItem, QMessageBox, QInputDialog, QLineEdit
# from PyQt5.QtWidgets.QObject import QTextDocument
from PyQt5.QtGui import QFont, QTextDocument

from Ui_transfer import Ui_MainWindowFFtransfer




_VER = "0.3.1"




class MainWindowFFtransfer(QMainWindow, Ui_MainWindowFFtransfer):

    CMD_TEMPLATE = "{FFMPEG} -i \"{ORIFILE}\" -vcodec prores_ks -profile {PROFILE} {OPTIONS} -acodec pcm_s16le \"{TARGETFILE}\""

    PROFILE_DICT = {
    "Apple Prores 422(Proxy)" : "'proxy'",
    "Apple Prores 422(LT)" : "'lt'",
    "Apple Prores 422" : "'standard'",
    "Apple Prores 422(HQ)" : "'hq'",
    "Apple Prores 4444" : "'4444'"
    }

    def __init__(self, parent=None):
        super(MainWindowFFtransfer, self).__init__(parent)
        self.setupUi(self)
        self.setupVariables()


    def setupVariables(self):
        self.ifCustomSize = False
        self.ifCustomRate = False
        self.ifCustomFfmpegPath = False
        self.fileList = []
        self.scriptList = []


    def refreshOriginList(self):
        """
        刷新列表
        """
        self.listWidgetOriginFiles.clear()
        self.listWidgetOriginFiles.addItems(self.fileList)


    def generateScript(self):
        """
        生成脚本
        """
        self.scriptList = []
        self.scriptList.append("#!/bin/sh")

        for originFile in self.fileList:

            ffmpegPath = "ffmpeg"
            if self.ifCustomFfmpegPath:
                ffmpegPath = self.lineEditFfmpegPath.text()

            profilecode = self.PROFILE_DICT[self.comboBoxOutputFormat.currentText()]

            targetpath = self.lineEditTargetPath.text()
            if targetpath:
                """
                如果指定了输出位置
                """
                ifUseDefaultTargetPath = False
            else:
                """
                如果输出位置栏是空的
                就在原始位置旁边新建 已转码文件夹
                """
                ifUseDefaultTargetPath = True
                originpath = os.path.split(originFile)[0]
                targetpath = os.path.join(originpath, "已转码")


            filename = os.path.basename(originFile)
            targetname = os.path.splitext(filename)[0] + ".MOV"
            targetfilename = os.path.join(targetpath,targetname)

            options = ""
            if self.ifCustomSize:
                sizeopt = "-s {WID}x{HEI} "
                sizeopt = sizeopt.format(WID=self.spinBoxWidth.value(), HEI=self.spinBoxHeight.value())
                options += sizeopt
            if self.ifCustomRate:
                rateopt = "-r {RATE} "
                rateopt = rateopt.format(RATE=self.spinBoxFrameRate.value())
                options += rateopt

            cmd = self.CMD_TEMPLATE.format(FFMPEG=ffmpegPath, ORIFILE=originFile, PROFILE=profilecode, OPTIONS=options, TARGETFILE=targetfilename)

            if ifUseDefaultTargetPath:
                """
                如果使用了默认位置
                """
                setupTargetPathCMD = "mkdir -p \"{TARPATH}\"".format(TARPATH=targetpath)
                self.scriptList.append(setupTargetPathCMD)

            self.scriptList.append(cmd)


    def refreshOutput(self):
        scriptText = "\n".join(self.scriptList)
        scriptText += "\n"
        doc = QTextDocument(scriptText)
        self.textEditOutput.setDocument(doc)


    @pyqtSlot()
    def on_actionIfCustomSize_triggered(self):
        self.ifCustomSize = self.checkBoxIfCustomSize.isChecked()
        self.labelSize.setEnabled(self.ifCustomSize)
        self.spinBoxWidth.setEnabled(self.ifCustomSize)
        self.spinBoxHeight.setEnabled(self.ifCustomSize)


    @pyqtSlot()
    def on_actionIfCustomRate_triggered(self):
        self.ifCustomRate = self.checkBoxIfCustomFrameRate.isChecked()
        self.spinBoxFrameRate.setEnabled(self.ifCustomRate)


    @pyqtSlot()
    def on_actionIfCustomFfmpegPath_triggered(self):
        self.ifCustomFfmpegPath = self.checkBoxIfCustomFfmpegPath.isChecked()
        self.labelFfmpegPath.setEnabled(self.ifCustomFfmpegPath)
        self.lineEditFfmpegPath.setEnabled(self.ifCustomFfmpegPath)
        self.toolButtonChooseFfmpegPath.setEnabled(self.ifCustomFfmpegPath)


    @pyqtSlot()
    def on_actionSetTargetPath_triggered(self):
        """
        选择目的位置
        """
        path = QFileDialog.getExistingDirectory(self, "选择目的位置", "")
        self.lineEditTargetPath.setText(path)


    @pyqtSlot()
    def on_actionSetFfmpegPath_triggered(self):
        path = QFileDialog.getOpenFileName(self, "选择FFMPEG程序", "ffmpeg", "FFMPEG(ffmpeg)")[0]
        self.lineEditFfmpegPath.setText(path)


    @pyqtSlot()
    def on_actionAddTask_triggered(self):
        flist = QFileDialog.getOpenFileNames(self, "选择原始文件", "", "所有文件(*)")[0]
        self.fileList += flist
        # print(self.fileList)
        self.refreshOriginList()


    @pyqtSlot()
    def on_actionRemoveTask_triggered(self):
        selection = self.listWidgetOriginFiles.selectedItems()
        if selection:
            for item in selection:
                selectedFileName = item.text()
                self.fileList.remove(selectedFileName)
            self.refreshOriginList()


    @pyqtSlot()
    def on_actionClearTask_triggered(self):
        self.fileList = []
        self.refreshOriginList()


    @pyqtSlot()
    def on_actionRefreshScript_triggered(self):
        self.generateScript()
        self.refreshOutput()


    @pyqtSlot()
    def on_actionSaveScript_triggered(self):
        scriptpath = QFileDialog.getSaveFileName(self, "保存转码脚本", "转码脚本.sh", "SHELL脚本(*.sh)")[0]
        if scriptpath:
            scriptText = ""
            lines = "\n".join(self.scriptList)
            scriptText += lines

            with open(scriptpath, "w", encoding="utf-8") as scriptFile:
                scriptFile.write(scriptText)



    @pyqtSlot()
    def on_actionAbout_triggered(self):
        from about import DialogAbout
        self.aboutdialog = DialogAbout(self)
        self.aboutdialog.setVersion(_VER)
        self.aboutdialog.exec()


    @pyqtSlot()
    def on_actionCopyScript_triggered(self):
        """
        拷贝脚本
        """
        self.textEditOutput.selectAll()
        self.textEditOutput.copy()
        self.statusbar.showMessage("脚本已拷贝至剪贴板。")





if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    window = MainWindowFFtransfer()
    window.show()
    sys.exit(app.exec_())
